from fastapi import APIRouter, Security, logger
from core.Auth import check_permissions
from core.Response import success, fail
from models.base import Category
from schemas.backend.category import CategoryAddReq, CategoryBatchReq
from tortoise.queryset import F
from core.Tree import Tree
import threading
import json

router = APIRouter()

@router.post(
    "",
    summary="栏目添加",
    dependencies=[Security(check_permissions, scopes=["category_add"])]
)
async def create_category(category: CategoryAddReq):
    """
    栏目添加
    :param category: CategoryAddReq
    :return:
    """
    await Category.create(**category.model_dump())
    return success(msg="添加成功")

@router.get(
    "/switch",
    summary="状态更新",
    dependencies=[Security(check_permissions, scopes=["category_update"])]
)
async def category_switch(type: int, cate_id: int, state: int):
    """
    状态更新
    :param  type: 类型
    :param cate_id: 栏目ID
    :param state: 状态
    :return:
    """
    if type == 1:
        await Category.filter(cate_id=cate_id).update(status=state)
    elif type == 2:
        await Category.filter(cate_id=cate_id).update(is_blank=state)
    return success(msg="更新成功")


@router.get(
    "",
    summary="栏目列表",
    dependencies=[Security(check_permissions, scopes=["category_list"])]
)
async def category_list():
    """
    栏目列表
    :return:
    """
    cate_data = await Category.all().order_by("-sort").values('cate_name', 'cate_id', 'cate_type', 'parent_id', 'is_blank', 'status', 'sort')
    cate_data = primevue_tree(cate_data, 0)
    return success(data=cate_data)

def primevue_tree(data, pid):
    """
    遍历栏目树
    :param data: cate[]
    :param parent_id: 父ID
    :return: list
    """
    result = []
    for item in data:
        if pid == item["parent_id"]:
            temp = primevue_tree(data, item["cate_id"])
            cate = {}
            cate['data'] = item
            cate['key'] = item["cate_id"]
            cate['label'] = item["cate_name"]
            if len(temp) > 0:
                cate["children"] = temp
            result.append(cate)
    return result

# 得到栏目树
@router.get(
    "/tree",
    summary="栏目树",
    dependencies=[Security(check_permissions, scopes=["category_tree"])]
)
async def category_tree():
    """
    栏目树
    :return:
    """
    category_list = await Category.annotate(key=F("cate_id"), label=F("cate_name")).filter(cate_type__in=[-1, 1, 2, 3]).all().values("key", "parent_id", "label", "cate_type")
    for item in category_list:
        if item["cate_type"] == -1:
            item["path"] = '/backend/content/page.html?classid='+str(item["key"])
        if item["cate_type"] == 1:
            item["path"] = '/backend/content/news/list.html?classid='+str(item["key"])
        if item["cate_type"] == 2:
            item["path"] = '/backend/content/pro/list.html?classid='+str(item["key"])
        if item["cate_type"] == 3:
            item["path"] = '/backend/content/job/list.html?classid='+str(item["key"])
        if item["cate_type"] == 4:
            item["path"] = '/backend/content/case/list.html?classid='+str(item["key"])
    tree_data = cate_tree(category_list, 0)
    return success(data=tree_data)
    
def cate_tree(data, pid):
    """
    遍历栏目树
    :param data: rule[]
    :param pid: 父ID
    :return: list
    """
    result = []
    for item in data:
        if pid == item["parent_id"]:
            temp = cate_tree(data, item["key"])
            if len(temp) > 0:
                item["children"] = temp
            result.append(item)
    return result

@router.post(
    "/batch",
    summary="栏目批量操作",
    dependencies=[Security(check_permissions, scopes=["category_batch"])]
)
async def batch_category(category: CategoryBatchReq):
    """
    栏目批量操作
    :param category: CategoryBatchReq
    :return:
    """
    types = category.type
    ids = category.id.split(",")
    if types == 1:
        await Category.filter(cate_id__in=ids).update(status=1)
        return success(msg="操作成功")
    if types == 2:
        await Category.filter(cate_id__in=ids).update(status=0)
        return success(msg="操作成功")
    if types == 3:
        await Category.filter(cate_id__in=ids).update(is_blank=1)
        return success(msg="操作成功")
    if types == 4:
        await Category.filter(cate_id__in=ids).update(is_blank=0)
        return success(msg="操作成功")
    elif types == 5:
        await Category.filter(cate_id__in=ids).delete()
        return success(msg="添加成功")

@router.get(
    "/refresh",
    summary="更新栏目缓存",
    dependencies=[Security(check_permissions, scopes=["category_refresh"])]
)
async def refresh_category():
    """
    更新栏目缓存
    :return:
    """
    try:
        # 步骤1：获取数据库数据（带异常处理）
        raw_data = await Category.all().values(
            "cate_id", 
            "cate_name", 
            "parent_id", 
            "cate_type", 
            "is_blank", 
            "status", 
            "sort"
        )
        
        if not raw_data:
            return success(msg="空数据集", data=[])
            
        # 步骤2：数据格式转换
        formatted_data = {
            item["cate_id"]: {
                "cateid": item["cate_id"],       # 适配字段名
                "followid": item["parent_id"],   # 父ID字段适配
                "name": item["cate_name"],
                "type": item["cate_type"],
                "is_blank": item["is_blank"],
                "status": item["status"],
                "sort": item["sort"]
            }
            for item in raw_data
        }
        
        # 步骤3：生成树形结构
        enhanced_tree = Tree.get_tree(formatted_data)

        file_lock = threading.Lock()
        try:
            with file_lock:
                with open("data/category.json", "w", encoding="utf-8") as f:
                    json.dump(enhanced_tree, f, ensure_ascii=False, indent=2)
        except Exception as e:
            return fail(f"保存栏目数据失败: {str(e)}")
        
        return success(
            msg="栏目缓存更新成功", 
            data=enhanced_tree
        )
        
    except Exception as e:
        logger.error(f"刷新栏目缓存失败: {str(e)}", exc_info=True)
        return fail(msg="缓存更新失败，请检查数据格式")